var app = getApp();
Page({
  data: {
    goods: {},
    goodsList: [],

    cart: {
    goods: {},
    goodsList: [],
    count: 0,//总数
    total: 0,//总价
    list: {},
    chooseGoodsArr: {},
    goodsIdArr: {}
  },
},
		showCartDetail: false,

	onLoad: function (options) {
    //获取菜品类型请求
    wx.request({
      url: 'http://localhost:8080/fullboy/queryTypes.action',
      method: "post",
      dataType: "json",
      success: res => {
        console.log(res.data.data)
        this.setData({
          goodsList: res.data.data
          
        }); 
        this.setData({
          classifySeleted: "a-"+this.data.goodsList[0].dTypeId
        });
      }
    }); 
    wx.request({
      url: 'http://localhost:8080/fullboy/queryFoods.action',
      method: "post",
      dataType: "json",
      success: res => {
        console.log(res.data.data)
        this.setData({
          goods: res.data.data
        }); 
        
      }
    });
   // 获取用户标识
    wx.login({
      success: function (res) {
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid: 'wx3c84453baf57dc5b',
            secret: 'e0d770b3f89f4a9bd7c8cb5ec609cbae',
            js_code: res.code,
            grant_type: 'authorization_code'
          },
          method: 'GET',
          success: function (res) {
            console.log(res);
            // 设置全局变量（用户标识）
            app.globalData.uSign = res.data.openid;
          }
        }),
        // 获取用户信息
        wx.getUserInfo({
          success: res => {
            // 可以将 res 发送给后台解码出 unionId
            // console.log(res);
            // 设置全局变量（用户昵称）
            app.globalData.uName = res.userInfo.nickName;
            // 
            wx.request({
              url: 'http://localhost:8080/fullboy/userlogin.action',
              data: {
                uSign: app.globalData.uSign,
                uName: app.globalData.uName
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
              },
              method: "post",
              dataType: "json",
              success: res => {
                console.log(res);
                app.globalData.uId = res.data.data;
                console.log(app.globalData.uName);
                console.log(app.globalData.uId);
              }
            });
            
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (this.userInfoReadyCallback) {
              this.userInfoReadyCallback(res)
            }
          }
        })
      }
    });
    
    
	},
  /**
   * 选好了,跳转到订单页面
   */
  orderPage: function () {
    let that = this.data.cart;
    var Allorderinfo = [];
    for (var key in that.list) {

      var cartCount = that.list[key]
      var temp = {};
      var orderinfo = JSON.stringify(this.data.goods[that.chooseGoodsArr[key]])
      temp[orderinfo] = cartCount;
      Allorderinfo.push(temp);
    }
    let Str = JSON.stringify(Allorderinfo);
    wx: wx.navigateTo({
      url: '../../pages/place_an_order/under?cart=' + Str,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })

  },
  onShow: function () {
   
	},
	tapAddCart: function (e) {
		this.addCart(e.target.dataset);
	},
	tapReduceCart: function (e) {
    console.log(e.target.dataset)
    this.reduceCart(e.target.dataset);
	},
  addCart: function (goodsInfo) {
    var data = this.data;
    var chooseGoodsArr = this.data.cart.chooseGoodsArr;
    //拼接字符串，前面是菜品类型Id 后面是菜品id
    var uniteKey = goodsInfo.id.dTypeId + "-" + goodsInfo.id.dId;
    
    for(var i=0;i<this.data.goods.length;i++){
      if (this.data.goods[i].dId == goodsInfo.id.dId && this.data.goods[i].dTypeId == goodsInfo.id.dTypeId){
        this.data.cart.chooseGoodsArr[uniteKey]  = i;
      }
    }

    var num = this.data.cart.list[uniteKey] || 0;
   
    this.data.cart.list[uniteKey] = num + 1;

		this.countCart();
	},

  reduceCart: function (goodsInfo) {
    console.log(this.data.cart.goods.count)
    var data = this.data;
    var chooseGoodsArr = this.data.cart.chooseGoodsArr;
    //拼接字符串，前面是菜品类型Id 后面是菜品id
    var uniteKey = goodsInfo.id.dTypeId + "-" + goodsInfo.id.dId;

    for (var i = 0; i < this.data.goods.length; i++) {
      if (this.data.goods[i].dId == goodsInfo.id.dId && this.data.goods[i].dTypeId == goodsInfo.id.dTypeId) {
        this.data.cart.chooseGoodsArr[uniteKey] = i;
      }
    }
    var num = this.data.cart.list[uniteKey] || 0;
		if (num <= 1) {
      delete this.data.cart.list[uniteKey];
		} else {
      this.data.cart.list[uniteKey] = num - 1;
		}
		this.countCart();
	},
  //  计算
	countCart: function () {
		var count = 0,
			total = 0;
		for (var id in this.data.cart.list) {
      var goods = this.data.goods[this.data.cart.chooseGoodsArr[id]];
			count += this.data.cart.list[id];
      console.log(this.data.cart)
      
      total += goods.dPrice * this.data.cart.list[id];
		}
		this.data.cart.count = count;
		this.data.cart.total = total;
		this.setData({
			cart: this.data.cart
		});
	},
	follow: function () {
		this.setData({
			followed: !this.data.followed
		});
	},
	onGoodsScroll: function (e) {
		if (e.detail.scrollTop > 10 && !this.data.scrollDown) {
			this.setData({
				scrollDown: true
			});
		} else if (e.detail.scrollTop < 10 && this.data.scrollDown) {
			this.setData({
				scrollDown: false
			});
		}

		var scale = e.detail.scrollWidth / 570,
			scrollTop = e.detail.scrollTop / scale,
			h = 0,
			classifySeleted,
			len = this.data.goodsList.length;
		this.data.goodsList.forEach(function (classify, i) {
      var _h = 70 + classify.dArr.length * (46 * 3 + 20 * 2);
			if (scrollTop >= h - 100 / scale) {
        classifySeleted ="a-"+classify.dTypeId;
        
      }
			h += _h;
		});
		this.setData({
			classifySeleted: classifySeleted
		});
	},
	tapClassify: function (e) {
		var id =e.target.dataset.id;
    console.log(id);
		this.setData({
			classifyViewed: id
		});
		var self = this;
		setTimeout(function () {
			self.setData({
				classifySeleted: id
			});
		}, 100);
	},
	showCartDetail: function () {
		this.setData({
			showCartDetail: !this.data.showCartDetail
		});
	},
	hideCartDetail: function () {
		this.setData({
			showCartDetail: false
		});
	}
});

